// pages/myself/myself.js
var util = require('../../utils/util.js');
var app = getApp()
var codes = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isOnload: false,
    isOnload_: false,
    userName: '尊敬的会员',
    userUrl: '/icons/nv.png',
    id: '',
    phone: '',
    index: 0,
    onload: 0,
    modalH: true,
    modalHidden: true,
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    kkk:0
  },
  shezhi:function(e){
    this.setData({
      isOnload_:true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.showLoading()
    
    if (wx.getStorageSync('kkk')==1) {
      this.setData({
        kkk : 1
    })
  }
    if (wx.getStorageSync('isOnload') == true) {
      this.setData({
        onload:1,
        isOnload: true,
        id: wx.getStorageSync('code'),
        index: wx.getStorageSync('index'),
        nickName:wx.getStorageSync('nickName'),
        avatarUrl: wx.getStorageSync('avatarUrl'),
      })
      console.log(111)
    }
    var time = util.formatTime(new Date());
    // 再通过setData更改Page()里面的data，动态更新页面的数据
    this.setData({
      time: time
    });
    console.log(time)
  },
  getUserProfile(e){
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          avatarUrl:res.userInfo.avatarUrl,
          nickName:res.userInfo.nickName,
          kkk:1
        })
        wx.setStorageSync('nickName', res.userInfo.nickName)
        wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl)
      }
    })
  
  },
  Confirm:function(e){
    var that = this
    this.setData({
      isOnload_:false,
      kkk:1
    })
    wx.setStorageSync('kkk', 1)
    // if(this.data.)
    let tableName = 'member'
    let Product = new wx.BaaS.TableObject(tableName)
    let product = Product.create()

    // 设置方式一
    let people = {
      code: that.data.id,
      phone: that.data.phone,
      avatarUrl:that.data.avatarUrl,
      nickName:that.data.nickName,
      openid:that.data.openid
    }
    console.log(people)
    product.set(people).save().then(res => {
      // success
      console.log(res)
      app.globalData.member_id = res.data.id
      wx.setStorageSync('dengji', 1)
    }, err => {

    })
  },

  wxLogin() {
    wx.login({
      success: (res) => {
        // 获取临时登录凭证 code
        codes = res.code
      }
    })
  },
  phoneNumberHandler(data) {
    var that = this
    wx.BaaS.auth.loginWithWechat(data, {
      // 通过 wx.login() 获取的临时登录凭证 code
      code: codes
    }).then(user => {
      console.log(user)
      console.log(user.openid)

      that.setData({
        openid:user.openid
      })
      app.globalData.phone = user._phone
      wx.showToast({
        title: '登录成功',
        icon: 'none', //如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      })
      that.setData({
        isOnload: true,
        phone: user._phone,
        // isOnload_: true
      })
      that.NumberHandler()
      wx.setStorageSync('isOnload', true)
      wx.setStorageSync('phone', user._phone)
      // this.NumberHandler()
      // user 包含用户完整信息，详见下方描述
    }, err => {
      wx.showToast({
        title: '登录失败',
        icon: 'none', //如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      })
      // **err 有两种情况**：用户拒绝授权，HError 对象上会包含基本用户信息：id、openid、unionid；其他类型的错误，如网络断开、请求超时等，将返回 HError 对象（详情见下方注解）
    })
  },
  tianjiayouhui:function(e){
    wx.navigateTo({
      url: '/pages/denglu/denglu',
    })
  },
  NumberHandler() {
    console.log(111)
    var that = this
    let tableName = 'member'
    let query = new wx.BaaS.Query()

    // 设置查询条件（比较、字符串包含、组合等）
    //...
    console.log(app.globalData.phone)
    query.compare('phone', '=', app.globalData.phone)
    // 应用查询对象
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(query).find().then(res => {
      // success
      console.log(res.data.objects.length)
      if (res.data.objects.length != 0) {
        that.setData({
          onload: 1,
          id: res.data.objects[0].code,
          avatarUrl:res.data.objects[0].avatarUrl,
          nickName:res.data.objects[0].nickName
        })
        wx.setStorageSync('youhui', res.data.objects[0].youhui)
        wx.setStorageSync('code', res.data.objects[0].code)
        wx.setStorageSync('onload', 1)
        wx.setStorageSync('nickName', res.data.objects[0].nickName)
        wx.setStorageSync('avatarUrl', res.data.objects[0].avatarUrl)
        console.log(res.data.objects[0].manager)
        if (res.data.objects[0].manager == 1) {
          that.setData({
            index: 1,
          })
          wx.setStorageSync('dengji', res.data.objects[0].dengji)
          wx.setStorageSync('index', 1)
        }else{
          wx.setStorageSync('index', 0)
        }
      }else{
        wx.setStorageSync('youhui', [])
        that.setMember()
        that.setData({
          isOnload_:true
        })
      }
     

    }, err => {
      // err
    })


  },
  tianjiashangping:function(e){
    setTimeout(function(E){
      wx.navigateTo({
        url: '/pages/logs/logs',
      })
    },200)
  },
  tianjiafuwurenyuan:function(E){
    setTimeout(function(E){
      wx.navigateTo({
        url: '/pages/jump/jump',
      })
    },200)
  },
  tianjiafuwu:function(E){
    setTimeout(function(E){
      wx.navigateTo({
        url: '/pages/picture/picture',
      })
    },200)
  },
  shou:function(E){
    wx.navigateTo({
      url: '/pages/shouhou/shouhou',
    })
  },
  pingdan:function(e){
    wx.navigateTo({
      url: '/pages/gouwu/gouwu',
    })
  },
  setMember() {
    console.log(222)
    var that = this
    console.log(that.data.onload)
    if (that.data.onload == 0) {
      wx.setStorageSync('onload', 0)
      var item = [
        ['G', 'H', 'I', 'J', 'K', 'L'],
        ['M', 'N', 'O', 'P', 'Q', 'R'],
        ['S', 'T', 'U', 'V', 'W', 'X'],
        ['Y', 'Z', 'K', '?', '/', '|'],
        ['7', '0', '@', '!', '~', '@'],
        ['1', '2', '3', '4', '5', '6'],
        ['$', '-', '=', '&', 'T', '#'],
        ['&', '9', '8', '%', '+', '#'],
        ['A', 'B', 'C', 'D', 'E', 'F'],
        ['S', '0' ,'D', 'K', 'M', 'O']
      ]
      if (this.data.index == 0) {
        var h = wx.getStorageSync('phone').split('')
        var id = ''
        var b
        var di = ''
        for (var j = 0; j < h.length; j++) {
          var a = Math.floor(Math.random() * 5)
          if (item[h[j]][a] <= 'Z' || item[h[j]][a] >= 'A') {
            b = Math.floor(Math.random())
            if (b == 1) {
              di = item[h[j]][a].toLowerCase()
              id = id.concat(di)
            } else {
              id = id.concat(item[h[j]][a])
            }
          }
          console.log(id)
        }
        this.setData({
          id: id,
 
        })
        console.log(this.data.id)
        wx.setStorageSync('ID', that.data.id)

      }
     
    }
  },
  Fenxi_Yonghu:function(e){
    setTimeout(function(E){
      wx.navigateTo({
        url: '/pages/shuju/shuju',
      })
    },300)
  },
  onFuZhiTap: function (e) {
    wx.setClipboardData({
      data: this.data.id,
    })
  },
  dingDan() {
    if (app.globalData.phone != '') {
      wx.navigateTo({
        url: '../dingdan/dingdan?id='+this.data.index,
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  },

  fuKuan() {
    if (app.globalData.phone != '') {
      wx.navigateTo({
        url: '../dingdan/dingdan?id='+this.data.index,
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  },
  daodian:function(E){
    wx.navigateTo({
      url: '/pages/dao/dao',
    })
  },
  faHuo() {
    if (app.globalData.phone != '') {
      wx.navigateTo({
        url: '../dingdan/dingdan?id='+this.data.index,
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  },


  yaoQing() {
    var that = this
    let tableName = 'member'

    let Query = new wx.BaaS.Query()
    Query.compare('phone', '=', that.data.phone) //判断
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
      // success
      console.log(res)
      that.setData({
        item: res.data.objects, //上门服务全部数据
        id: res.data.objects[0].id
      })
      app.globalData.item = that.data.item
      app.globalData.id = that.data.id
    }, err => {
      // err
    })
    if (app.globalData.phone != '') {
      wx.navigateTo({
        url: '../yaoqing/yaoqing',
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  },

  shouCang() {
    if (app.globalData.phone != '') {
      wx.navigateTo({
        url: '../shoucang/shoucang',
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  },
  //售后
  shouhou: function (e) {
    wx.makePhoneCall({
      phoneNumber: '400-777-1820',
    })
  },
  diZhi: function (e) {
    var time = setTimeout(function (e) {
      wx.navigateTo({
        url: '/pages/addresDetail/addresDetail',
      })
    }, 200)
    // clearTimeout(time)
  },

  /**
   * 建立入驻信息
   */

  setRuZhu: function (e) {
    this.setData({
      modalH: false
    })
    let tableName = 'dianpu'
    let query = new wx.BaaS.Query()

    // 设置查询条件（比较、字符串包含、组合等）
    //...
    query.compare('isreturn', '=', 0)
    // 应用查询对象
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(query).find().then(res => {
      // success
      this.setData({
        ruzhu: res.data.objects
      })
    }, err => {
      // err
    })
  },
  /**
   * 获取店铺信息
   */
  getruzhu: function (e) {
    this.setData({
      ruzhudianpu: e.detail.value
    })
  },
  getlianxiren: function (e) {
    this.setData({
      lianxiren: e.detail.value
    })
  },
  /**
   * 获取入驻信息
   */
  getRuZhu: function (e) {
    this.setData({
      modalHidden: false
    })

  },
  modalConfirm: function (e) {
    this.setData({
      modalHidden: true
    })
    let tableName = 'dianpu'
    let Product = new wx.BaaS.TableObject(tableName)
    let product = Product.create()

    // 设置方式一
    let apple = {
      name: this.data.ruzhudianpu,
      phone: this.data.lianxiren,
    }

    product.set(apple).save().then(res => {
      // success
      console.log(res)
      wx.showToast({
        title: '填写完成！客服人员会在三个工作日内联系您',
        icon: 'none'
      })
    }, err => {
      //err 为 HError 对象
    })
  },
  modalCandel: function (e) {
    this.setData({
      modalHidden: true
    })

  },
  modalHConfirm: function (e) {
    this.setData({
      modalH: true
    })

  },
  modalHCandel: function (e) {
    this.setData({
      modalH: true
    })
  },
  yilianxi: function (e) {
    console.log(e.currentTarget.dataset.postid)
    var postid = e.currentTarget.dataset.postid
    let tableName = 'dianpu'
    let recordID = this.data.ruzhu[postid].id // 数据行 id

    let Product = new wx.BaaS.TableObject(tableName)
    let product = Product.getWithoutData(recordID)

    product.set('isreturn', 1)
    product.update().then(res => {
      // success
      wx.showToast({
        title: '已处理该信息，可在后台查看',
        icon: 'none'
      })
    }, err => {
      // err
    })
  },
  goHuiyuan: function (e) {
    wx.navigateTo({
      url: '/pages/huiyuan/huiyuan',
    })
  }
})